package cool.mtc.base.plugin.generator.code;

import cool.mtc.base.plugin.generator.code.controller.CodeGeneratorController;
import cool.mtc.base.plugin.generator.code.service.CodeGeneratorService;
import cool.mtc.base.plugin.generator.code.service.impl.CodeGeneratorServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 明河
 */
@Slf4j
@Configuration
@ConditionalOnProperty(value = "mtc.generator.code.enabled", havingValue = "true", matchIfMissing = true)
@Import({
        CodeGeneratorController.class,
})
@EnableConfigurationProperties(value = {CodeGeneratorProperties.class})
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CodeGeneratorConfig {
    private final CodeGeneratorProperties codeGeneratorProperties;

    @Bean
    public CodeGeneratorService codeGeneratorService() throws IOException {
        return new CodeGeneratorServiceImpl(this.codeGeneratorConfiguration(), codeGeneratorProperties);
    }

    @Bean
    public freemarker.template.Configuration codeGeneratorConfiguration() throws IOException {
        freemarker.template.Configuration configuration = new freemarker.template.Configuration(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(StandardCharsets.UTF_8.displayName());
        configuration.setDirectoryForTemplateLoading(ResourceUtils.getFile(codeGeneratorProperties.getTemplateBasePath()));
        return configuration;
    }
}
